import { NextRequest, NextResponse } from 'next/server';
import { cars } from '@/data/cars';

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const page = parseInt(searchParams.get('page') || '1');
    const pageSize = parseInt(searchParams.get('pageSize') || '10');
    const keyword = searchParams.get('keyword') || '';
    const brand = searchParams.get('brand') || '';
    const type = searchParams.get('type') || '';
    const priceMin = searchParams.get('priceMin');
    const priceMax = searchParams.get('priceMax');
    const fuelType = searchParams.get('fuelType') || '';
    const yearMin = searchParams.get('yearMin');
    const yearMax = searchParams.get('yearMax');
    const mileageMin = searchParams.get('mileageMin');
    const mileageMax = searchParams.get('mileageMax');
    const transmission = searchParams.get('transmission') || '';
    const color = searchParams.get('color') || '';

    // 模拟API延迟
    await new Promise(resolve => setTimeout(resolve, 200));

    let filteredCars = [...cars];

    // 关键词搜索
    if (keyword) {
      filteredCars = filteredCars.filter(car => 
        car.name.toLowerCase().includes(keyword.toLowerCase()) ||
        car.brand.toLowerCase().includes(keyword.toLowerCase())
      );
    }

    // 品牌筛选
    if (brand) {
      filteredCars = filteredCars.filter(car => car.brand === brand);
    }

    // 新车/二手车筛选
    if (type) {
      filteredCars = filteredCars.filter(car => car.type === type);
    }

    // 价格范围筛选
    if (priceMin && priceMax) {
      filteredCars = filteredCars.filter(car => 
        car.price >= parseInt(priceMin) && car.price <= parseInt(priceMax)
      );
    }

    // 燃料类型筛选
    if (fuelType) {
      filteredCars = filteredCars.filter(car => car.fuelType === fuelType);
    }

    // 年份范围筛选
    if (yearMin && yearMax) {
      filteredCars = filteredCars.filter(car => 
        car.year >= parseInt(yearMin) && car.year <= parseInt(yearMax)
      );
    }

    // 里程筛选（仅二手车）
    if (type === 'used' && mileageMin && mileageMax) {
      filteredCars = filteredCars.filter(car => 
        car.mileage && car.mileage >= parseInt(mileageMin) && car.mileage <= parseInt(mileageMax)
      );
    }

    // 变速箱筛选
    if (transmission) {
      filteredCars = filteredCars.filter(car => car.specifications.transmission === transmission);
    }

    // 颜色筛选
    if (color) {
      filteredCars = filteredCars.filter(car => car.color === color);
    }

    // 分页逻辑
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedCars = filteredCars.slice(startIndex, endIndex);

    // 统计数据
    const brands = [...new Set(filteredCars.map(car => car.brand))];
    const newCars = filteredCars.filter(car => car.type === 'new').length;
    const usedCars = filteredCars.filter(car => car.type === 'used').length;
    const avgPrice = filteredCars.reduce((sum, car) => sum + car.price, 0) / filteredCars.length;

    return NextResponse.json({
      code: 200,
      message: 'success',
      data: {
        cars: paginatedCars,
        total: filteredCars.length,
        page,
        pageSize,
        stats: {
          totalCars: filteredCars.length,
          newCars,
          usedCars,
          brandsCount: brands.length,
          avgPrice: Math.round(avgPrice)
        }
      },
      timestamp: Date.now()
    });
  } catch (error) {
    return NextResponse.json({
      code: 500,
      message: 'Internal server error',
      data: null,
      timestamp: Date.now()
    }, { status: 500 });
  }
}